package module

import (
	"context"
	"fmt"
	zaprotatelogs "github.com/lestrrat-go/file-rotatelogs"
	. "go-admin/src/util"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/utils"
	"os"
	"path"
	"time"
)

var level zapcore.Level
var zapLog      *zap.Logger
func GetLogger() *zap.Logger{
	return zapLog
}
func Logger(level string,info string,fieldinfo interface{}){

	z:=zap.Any(level,fieldinfo)

	switch level { // 初始化配置文件的Level
	case "debug":
		zapLog.Debug(info,z)
	case "info":
		zapLog.Info(info,z)
	case "warn":
		zapLog.Warn(info,z)
	case "error":
		zapLog.Error(info,z)
	case "dpanic":
		zapLog.DPanic(info,z)
	case "panic":
		zapLog.Panic(info,z)
	case "fatal":
		zapLog.Fatal(info,z)
	default:
		zapLog.Info(info,z)
	}


}

type zaplogger struct {
	logger.Writer
	logger.Config
	LogLevel logger.LogLevel
}
func (l *zaplogger) LogMode(level logger.LogLevel) logger.Interface {
	newlogger := *l
	newlogger.LogLevel = level
	return &newlogger
}

// Info print info
func (l zaplogger) Info(ctx context.Context, msg string, data ...interface{}) {

	if l.LogLevel >= logger.Info {
		//fmt.Println(data)
		zapLog.Sugar().Infow(msg, "line",utils.FileWithLineNum(), "data",data)

		//ZapLog.Info(msg+utils.FileWithLineNum(),zap.Any("info",data))
	}
}

// Warn print warn messages
func (l zaplogger) Warn(ctx context.Context, msg string, data ...interface{}) {
	if l.LogLevel >= logger.Warn {
		zapLog.Sugar().Warnw(msg,"line",utils.FileWithLineNum(), "data",data)
	}
}

// Error print error messages
func (l zaplogger) Error(ctx context.Context, msg string, data ...interface{}) {
	if l.LogLevel >= logger.Error {
		zapLog.Sugar().Errorw(msg,"line",utils.FileWithLineNum(), "data",data)
	}
}

// Trace print sql message
func (l zaplogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	if l.LogLevel > 0 {
		elapsed := time.Since(begin)
		switch {
		case err != nil && l.LogLevel >= logger.Error:
			sql, rows := fc()
			if rows == -1 {
				zapLog.Sugar().Errorw(
					"errorstr",
					"line",utils.FileWithLineNum(),
					               "error",err,
					               "time",float64(elapsed.Nanoseconds())/1e6,
					               "-", sql)
			} else {
				zapLog.Sugar().Errorw(
					"errorstr",
					"line",utils.FileWithLineNum(),
					"error",err,
					"time",float64(elapsed.Nanoseconds())/1e6,
					"rows",rows,
					"sql",sql)
			}
		case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= logger.Warn:
			sql, rows := fc()
			slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
			if rows == -1 {
				zapLog.Sugar().Warnw(
					"warnstr",
					"line",utils.FileWithLineNum(),
					"slowLog",slowLog,
					"time",float64(elapsed.Nanoseconds())/1e6,
					"-", sql)
			} else {
				zapLog.Sugar().Warnw(
					"",
					"line",utils.FileWithLineNum(),
					"slowLog",slowLog,
					"time",float64(elapsed.Nanoseconds())/1e6,
					"rows",rows,
					"sql",sql)
			}
		case l.LogLevel >= logger.Info:
			sql, rows := fc()
			if rows == -1 {
				zapLog.Sugar().Infow(
					"infostr",
					"line",utils.FileWithLineNum(),
					"time",float64(elapsed.Nanoseconds())/1e6,
					"-",
					sql)
			} else {
				zapLog.Sugar().Infow(
					"infostr",
					"line",utils.FileWithLineNum(),
					"time",float64(elapsed.Nanoseconds())/1e6,
					"rows",rows,
					"sql",sql)
			}
		}
	}
}




func InitZap() {

	if ok, _ := PathExists(DefaultConf.Zap.Director); !ok { // 判断是否有Director文件夹
		//创建日志文件夹
		_ = os.Mkdir(DefaultConf.Zap.Director, os.ModePerm)
	}
	switch DefaultConf.Zap.Level { // 初始化配置文件的Level
	case "debug":
		level = zap.DebugLevel
	case "info":
		level = zap.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}

	if level == zap.DebugLevel || level == zap.ErrorLevel {
		zapLog = zap.New(getEncoderCore(), zap.AddStacktrace(level))
	} else {
		zapLog = zap.New(getEncoderCore())
	}
	if DefaultConf.Zap.ShowLine {
		zapLog.WithOptions(zap.AddCaller())
	}


}

// getEncoderConfig 获取zapcore.EncoderConfig
func getEncoderConfig() (zpconfig zapcore.EncoderConfig) {
	zpconfig = zapcore.EncoderConfig{
		MessageKey:     "message",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "logger",
		CallerKey:      "caller",
		StacktraceKey:  DefaultConf.Zap.StacktraceKey,
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     CustomTimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
	}
	switch {
	case DefaultConf.Zap.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
		zpconfig.EncodeLevel = zapcore.LowercaseLevelEncoder
	case DefaultConf.Zap.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
		zpconfig.EncodeLevel = zapcore.LowercaseColorLevelEncoder
	case DefaultConf.Zap.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
		zpconfig.EncodeLevel = zapcore.CapitalLevelEncoder
	case DefaultConf.Zap.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
		zpconfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	default:
		zpconfig.EncodeLevel = zapcore.LowercaseLevelEncoder
	}
	return zpconfig
}

// getEncoder 获取zapcore.Encoder
func getEncoder() zapcore.Encoder {
	if DefaultConf.Zap.Format == "json" {
		return zapcore.NewJSONEncoder(getEncoderConfig())
	}
	return zapcore.NewConsoleEncoder(getEncoderConfig())
}

// getEncoderCore 获取Encoder的zapcore.Core
func getEncoderCore() (core zapcore.Core) {
	writer, err := GetWriteSyncer() // 使用file-rotatelogs进行日志分割
	if err != nil {
		fmt.Printf("Get Write Syncer Failed err:%v", err.Error())
		return
	}
	return zapcore.NewCore(getEncoder(), writer, level)
}

// 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format(DefaultConf.Zap.Prefix + "2006/01/02 - 15:04:05.000"))
}
// GetWriteSyncer zap logger中加入file-rotatelogs
func GetWriteSyncer() (zapcore.WriteSyncer, error) {
	fileWriter, err := zaprotatelogs.New(
		path.Join(DefaultConf.Zap.Director, "%Y-%m-%d.log"),
		zaprotatelogs.WithMaxAge(7*24*time.Hour),
		zaprotatelogs.WithRotationTime(24*time.Hour),
	)
	if DefaultConf.Zap.LogInConsole {
		return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err
	}
	return zapcore.AddSync(fileWriter), err
}